package com.simtop.util;

import com.alibaba.fastjson.JSONObject;
import com.simtop.common.Key;
import com.simtop.pojo.ilabresult.IlabSport;
import com.simtop.util.httputil.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;


/**
 * @author lvyognwei
 * @description 上传ilab的工具类  2.0接口
 *
 *     上传方式  http://shenbao.ilab-x.com/declare/wiki/v2#3
 */
@Configuration
public class IlabUtil {

    /**
     * 获取access_token   正式上线使用正式地址
     */
    private String ACCESS_TOKEN = "http://www.ilab-x.com/open/api/v2/token";
    /*private String ACCESS_TOKEN = "http://202.205.145.156:8017/open/api/v2/token";*/
    /**
     * 提交成绩
     */
    private String SUBMIT_GRADE = "http://www.ilab-x.com/open/api/v2/data_upload";
    /*private String SUBMIT_GRADE = "http://202.205.145.156:8017/open/api/v2/data_upload";*/

    private Logger log = LoggerFactory.getLogger(IlabUtil.class);

    /**
     * 获取access_token
     * @param ticket
     * @return    json字符串
     */
    public String getAccessToken(String ticket) throws UnsupportedEncodingException {
        //ticket解密
        String rTicket = URLDecoder.decode(ticket,"UTF-8");
        //获取signature  （按照要求进行MD5加密，这是自己定义的工具类方法）
        String signature = CipherUtil.generatePassword(rTicket+ Key.issuerId + Key.AesKey);
        //发送请求获取access_key
        String url = ACCESS_TOKEN + "?ticket=" + ticket + "&appid=" + Key.issuerId + "&signature="+signature;
        String result = "";
        try{
            result = HttpClientUtil.doGet(url);
            System.err.println(result);
            return result;
        }catch (Exception e){
            log.error("{}获取access_token失败{}",new Date(),result);
            return null;
        }
    }

    /**
     * 提交成绩
     * @return
     */
    public String submitGrade(IlabSport ilabSport,String accessToken){
        System.out.println(JSONObject.toJSONString(ilabSport));
        String data = JSONObject.toJSONString(ilabSport);
        String url = SUBMIT_GRADE + "?access_token=" + accessToken;
        String result ="";
        try{
            result = HttpClientUtil.doPost(url,data);
            System.out.println(result);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            log.error("{}上传成绩失败{}",new Date(),result);
            return null;
        }
    }
}
